#include "server_socket.h"
#include "rk_defines.h"
#include "rk_debug.h"
#include <ifaddrs.h>
#include <arpa/inet.h>

std::mutex ServerSocket::log_mutex;
int ServerSocket::current_client_socket = -1; // 初始化
std::atomic<time_t> ServerSocket::last_data_time;
std::vector<unsigned char> ServerSocket::remainingData;
// 定义二进制心跳消息
const std::array<unsigned char, 2> ServerSocket::HEARTBEAT_MSG = {MSG_HEARTBEAT, 0x00};
std::atomic<int> ServerSocket::missed_heartbeats;
// 定义广播线程
std::mutex ServerSocket::broadcast_mutex;
std::atomic<bool> ServerSocket::broadcasting;
std::condition_variable ServerSocket::broadcast_cv;

tConnectStateCallback *s_connectStateCallback = NULL; // 定义回调方法变量
tMsgCallback *s_msgCallback = NULL;
// 定义断开指令
const std::array<unsigned char, 8> ServerSocket::CLOSE_SOCKET_MSG = {MSG_SEND_IP, 0x06, IP_0X_255, IP_0X_255, IP_0X_255, IP_0X_255, PORT_0X_00, PORT_0X_00};
// 定义解析错误指令
const std::array<unsigned char, 2> ServerSocket::ERROR_SOCKET_MSG = {ERROR_MSG, 0x00};
// 定义解析正确指令
const std::array<unsigned char, 2> ServerSocket::CORRECT_SOCKET_MSG = {CORRECT_MSG, 0x00};
ServerSocket::ServerSocket()
{
}

ServerSocket::~ServerSocket()
{
}

bool ServerSocket::init(tConnectStateCallback connect_state, tMsgCallback msg, int ipSet)
{
    if (connect_state != NULL)
        s_connectStateCallback = connect_state;
    if (msg != NULL)
        s_msgCallback = msg;

    addrlen = sizeof(address);
    subnet = ipSet;

    // 0. 获取设备编号
    std::string deviceCode = findDeviceCode();
    if (!deviceCode.empty())
    {
        std::cout << "Matching device code: " << deviceCode << std::endl;
        devicesId = deviceCode;
    }
    else
    {
        std::cout << "No matching device code found." << std::endl;
    }

    // 1. 创建套接字
    server_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (server_fd == 0)
    {
        std::cerr << "Socket creation faile!" << std::endl;
        return false;
    }

    // 2. 设置地址参数并绑定
    address.sin_family = AF_INET;         // IPv4
    address.sin_addr.s_addr = INADDR_ANY; // 绑定到本地 IP
    address.sin_port = htons(PORT);       // 转换为网络字节序

    if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0)
    {
        std::cerr << "Bind failed!" << std::endl;
        return false;
    }

    // 3. 开始监听
    if (listen(server_fd, 1) < 0)
    { // 只允许一个连接在队列中等待
        std::cerr << "Listen failed!" << std::endl;
        return false;
    }

    printf("Server initialized and listening on port %d ...\n", PORT);
    printf("Only one client is allowed to connect at a time.\n");

    // 开启广播线程
    broadcasting = true;
    is_running = true;
    broadcast_thread = std::thread(&ServerSocket::broadcastLoop, this);

    return true;
}
void ServerSocket::broadcastLoop()
{
    int broadcastSocket;
    struct sockaddr_in broadcastAddr;
    unsigned char message[10]; //// 修改为二进制格式，固定长度为 10 字节

    // 创建 UDP Socket
    broadcastSocket = socket(AF_INET, SOCK_DGRAM, 0);
    if (broadcastSocket < 0)
    {
        perror("Socket creation failed in broadcast loop");
        exit(EXIT_FAILURE);
    }

    // 设置广播选项
    int broadcastEnable = 1;
    if (setsockopt(broadcastSocket, SOL_SOCKET, SO_BROADCAST, &broadcastEnable, sizeof(broadcastEnable)) < 0)
    {
        perror("Enable broadcast option failed");
        close(broadcastSocket);
        exit(EXIT_FAILURE);
    }

    // 配置广播地址
    memset(&broadcastAddr, 0, sizeof(broadcastAddr));
    broadcastAddr.sin_family = AF_INET;
    broadcastAddr.sin_port = htons(8888); // UDP 广播固定端口
    // broadcastAddr.sin_addr.s_addr = INADDR_BROADCAST;
    // 构建 IP 地址字符串
    char ip_address[16];
    snprintf(ip_address, sizeof(ip_address), "192.168.%d.255", subnet);
    broadcastAddr.sin_addr.s_addr = inet_addr(ip_address); // 广播地址;

    // 填充广播消息
    message[0] = MSG_SEND_IP; // 固定值
    message[1] = 0x0a;        // 固定值

    // 构造广播消息 将文本 IP 地址转换为二进制格式 (IPv4)
    std::string localIP = getLocalIPAddress();
    struct in_addr ip_addr;
    if (inet_pton(AF_INET, localIP.c_str(), &ip_addr) != 1)
    {
        perror("Invalid IP address");
        close(broadcastSocket);
        return;
    }
    memcpy(&message[2], &ip_addr, 4); // 拷贝 4 字节的 IP 地址

    // 将端口号转换为网络字节序，并填充到消息中
    uint16_t port = htons(PORT);   // 将端口号转换为网络字节序
    memcpy(&message[6], &port, 2); // 拷贝 2 字节的端口号

    int temp = std::stoi(devicesId);
    if (temp < 0 || temp > 65535)
    {
        std::cerr << "Value out of uint16_t range" << std::endl;
    }
    uint16_t deviceNum = static_cast<uint16_t>(temp);
    uint8_t highByte = (deviceNum >> 8) & 0xFF; // 高字节
    uint8_t lowByte = deviceNum & 0xFF;         // 低字节

    memcpy(&message[8], &highByte, 1);
    memcpy(&message[9], &lowByte, 1);

    printf("Broadcast thread started, message is [%02x %02x %02x %02x %02x %02x %02x %02x %02x %02x].\n",
           message[0], message[1], message[2], message[3], message[4], message[5], message[6], message[7], message[8], message[9]);

    // 循环发送广播消息
    while (is_running)
    {
        // 判断是否需要广播（广播控制逻辑）
        std::unique_lock<std::mutex> lock(broadcast_mutex);
        broadcast_cv.wait(lock, [this]()
                          { return broadcasting || !is_running; }); // 阻塞等待广播开启或服务停止

        if (!is_running)
        {
            break; // 如果服务端停止，则退出线程
        }

        // 发送广播消息
        if (sendto(broadcastSocket, message, sizeof(message), 0, (struct sockaddr *)&broadcastAddr, sizeof(broadcastAddr)) < 0)
        {
            std::cerr << "Broadcast failed!" << std::endl;
        }
        else
        {
            printf("Broadcast message: %d %d %d.%d.%d.%d:%d:%d\n", message[0], message[1], message[2], message[3], message[4], message[5], combineBytes(message[6], message[7]), combineBytes(message[8], message[9]));
        }

        lock.unlock();                                        // 解锁互斥锁
        std::this_thread::sleep_for(std::chrono::seconds(2)); // 每隔 2 秒广播一次
    }

    close(broadcastSocket);
    printf("Broadcast thread stopped.\n");
}

std::string ServerSocket::getLocalIPAddress()
{
    struct ifaddrs *ifaddr, *ifa;
    char host[NI_MAXHOST];

    if (getifaddrs(&ifaddr) == -1)
    {
        perror("getifaddrs");
        return "";
    }

    // 遍历本机网络接口
    for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next)
    {
        if (ifa->ifa_addr == NULL)
            continue;
        if (ifa->ifa_addr->sa_family == AF_INET)
        { // IPv4
            if (getnameinfo(ifa->ifa_addr, sizeof(struct sockaddr_in), host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST) == 0)
            {
                if (strcmp(host, "127.0.0.1") != 0)
                { // 跳过回环地址
                    freeifaddrs(ifaddr);
                    return host;
                }
            }
        }
    }

    freeifaddrs(ifaddr);
    return "";
}

void ServerSocket::run()
{
    while (is_running)
    {
        if (current_client_socket != -1)
        {
            std::this_thread::sleep_for(std::chrono::seconds(1));
            continue;
        }

        int client_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t *)&addrlen);
        if (client_socket < 0)
        {
            if (is_running)
            {
                std::cerr << "Accept failed!" << std::endl;
            }
            continue;
        }

        // 停止广播
        {
            std::lock_guard<std::mutex> lock(broadcast_mutex);
            broadcasting = false;
        }
        broadcast_cv.notify_one(); // 通知广播线程停止广播

        // 设置接收超时为5秒(心跳间隔)
        struct timeval tv;
        tv.tv_sec = 5;
        tv.tv_usec = 0;
        setsockopt(client_socket, SOL_SOCKET, SO_RCVTIMEO, (const char *)&tv, sizeof(tv));

        current_client_socket = client_socket;
        printf("Client connected (socket: %d)\n", client_socket);
        if (s_connectStateCallback != NULL)
            s_connectStateCallback(true);

        pthread_t thread_id;
        pthread_create(&thread_id, nullptr, handleClient, (void *)(intptr_t)client_socket);
        client_thread = thread_id;

        // pthread_t thread_heartbert;
        // pthread_create(&thread_heartbert, nullptr, sendHeartbeat, (void *)(intptr_t)client_socket);
        // heartbert_thread = thread_heartbert;
    }
}

bool ServerSocket::sendData(const void *data, size_t length)
{
    // 1. 检查客户端连接状态
    if (current_client_socket == -1)
    {
        std::cerr << "Error: No client connected" << std::endl;
        return false;
    }

    // 2. 发送数据（支持断点续传）
    size_t total_sent = 0;
    while (total_sent < length)
    {
        ssize_t bytes_sent = send(current_client_socket,
                                  static_cast<const char *>(data) + total_sent,
                                  length - total_sent,
                                  0);

        // 3. 错误处理
        if (bytes_sent == -1)
        {
            if (errno == EINTR)
                continue; // 被信号中断则重试
            perror("[网络错误] 发送失败");
            return false;
        }

        // 4. 记录已发送字节数
        total_sent += bytes_sent;
    }
    last_data_time = time(nullptr);

    return true;
}



void *ServerSocket::handleClient(void *arg)
{
    int client_socket = (intptr_t)arg;
    unsigned char buffer[BUFFER_SIZE] = {0};
    memset(buffer, 0, BUFFER_SIZE);

    std::atomic<bool> client_active(true);
    missed_heartbeats.store(0); // 重置心跳计数器

    while (client_active)
    {
        int len = read(client_socket, buffer, BUFFER_SIZE);
        if (len > 0)
        {
            // buffer[len] = '\0';
            // std::string message(buffer);
            processReceivedData(buffer, len, client_socket);

            /*
                        // 检查是否为心跳指令
                        if (isHeartbeat(buffer, len))
                        {
                            missed_heartbeats.store(0); // 收到心跳，重置计数器
                            printf("Received heartbeat from client (socket: %d)\n", client_socket);
                            continue;
                        }

                        // 检查是否为断开连接指令
                        if (isCloseCommand(buffer, len))
                        {
                            printf("Client (socket: %d) sent exit command\n", client_socket);
                            send(client_socket, CORRECT_SOCKET_MSG.data(), CORRECT_SOCKET_MSG.size(), 0);
                            last_data_time = time(nullptr);
                            client_active = false;
                            break;
                        }

                        // 检查是否为设置类：数据类型指令
                        if (isSetDataTypeCommand(buffer, len))
                        {
                            printf("Client (socket: %d) sent setting dataType command\n", client_socket);
                            send(client_socket, CORRECT_SOCKET_MSG.data(), CORRECT_SOCKET_MSG.size(), 0);
                            last_data_time = time(nullptr);
                            // 获取匹配的枚举值
                            RequestType requestType = getRequestType(combineBytes(buffer[2], buffer[3]));
                            RequestTag requsetTag = getRequestTag(combineBytes(buffer[4], buffer[5]));

                            Request req(requestType, requsetTag, 0, 0);
                            if (s_msgCallback != NULL)
                                s_msgCallback(MSG_SET_DATA_TYPE, req);
                            else
                                std::cerr << "Error: on callback set!" << std::endl;
                            continue;
                        }

                        // 检查是否为设置类：模型参数指令
                        if (isSetModelCommand(buffer, len))
                        {
                            printf("Client (socket: %d) sent setting model command\n", client_socket);
                            send(client_socket, CORRECT_SOCKET_MSG.data(), CORRECT_SOCKET_MSG.size(), 0);
                            last_data_time = time(nullptr);
                            // 获取匹配的枚举值
                            RequestType requestType = getRequestType(combineBytes(buffer[2], buffer[3]));
                            RequestTag requsetTag = getRequestTag(combineBytes(buffer[4], buffer[5]));
                            int modelVersion = combineBytes(buffer[6], buffer[7]);
                            Request req(requestType, requsetTag, 0, modelVersion);
                            if (s_msgCallback != NULL)
                                s_msgCallback(MSG_SET_MODEL, req);
                            else
                                std::cerr << "Error: on callback set!" << std::endl;
                            continue;
                        }

                        // 检查是否为设置类：更改数据请求长度指令
                        if (isSetDataLenCommand(buffer, len))
                        {
                            printf("Client (socket: %d) sent setting dataLen command\n", client_socket);
                            send(client_socket, CORRECT_SOCKET_MSG.data(), CORRECT_SOCKET_MSG.size(), 0);
                            last_data_time = time(nullptr);
                            uint32_t dataLen = combineTo32Bit(buffer[2], buffer[3], buffer[4], buffer[5]);
                            Request req(RequestType::NONE, RequestTag::NONE, dataLen, 0);
                            if (s_msgCallback != NULL)
                                s_msgCallback(MSG_SET_DATA_MS, req);
                            else
                                std::cerr << "Error: on callback set!" << std::endl;
                            continue;
                        }

                        // 检查是否为pc端请求主动请求数据发送指令
                        if (isPcRequestCommand(buffer, len))
                        {
                            printf("Client (socket: %d) sent request data command\n", client_socket);
                            send(client_socket, CORRECT_SOCKET_MSG.data(), CORRECT_SOCKET_MSG.size(), 0);
                            last_data_time = time(nullptr);
                            Request req;
                            if (s_msgCallback != NULL)
                                s_msgCallback(MSG_REQUEST, req);
                            else
                                std::cerr << "Error: on callback set!" << std::endl;
                            continue;
                        }

                        // 检查是否为pc端请求耳机电量信息指令
                        if (isPcRequestBatteryCommand(buffer, len))
                        {
                            printf("Client (socket: %d) sent request battery command\n", client_socket);
                            send(client_socket, CORRECT_SOCKET_MSG.data(), CORRECT_SOCKET_MSG.size(), 0);
                            last_data_time = time(nullptr);
                            Request req;
                            if (s_msgCallback != NULL)
                                s_msgCallback(MSG_REQUEST_BATTERY, req);
                            else
                                std::cerr << "Error: on callback set!" << std::endl;
                            continue;
                        }

                        // 检查是否为pc端请求更改图像请求分辨率
                        if (isSetPixelsCommand(buffer, len))
                        {
                            printf("Client (socket: %d) sent request pixels command\n", client_socket);
                            send(client_socket, CORRECT_SOCKET_MSG.data(), CORRECT_SOCKET_MSG.size(), 0);
                            last_data_time = time(nullptr);
                            uint32_t pixelsW = combineBytes(buffer[2], buffer[3]);
                            uint32_t pixelsH = combineBytes(buffer[4], buffer[5]);
                            Request req(RequestType::NONE, RequestTag::NONE, 0, 0, pixelsW, pixelsH);
                            if (s_msgCallback != NULL)
                                s_msgCallback(MSG_SET_PIXESL_WH, req);
                            else
                                std::cerr << "Error: on callback set!" << std::endl;
                            continue;
                        }
                        */

            // send(client_socket, ERROR_SOCKET_MSG.data(), ERROR_SOCKET_MSG.size(), 0);
            last_data_time = time(nullptr);

            // send(client_socket, buffer, sizeof(buffer), 0);
            // buffer[len] = '\0'; // 假设 BUFFER_SIZE >= len + 1
            // 处理普通消息
            // printf("Message from client (socket: %d): %s, length is %d\n", client_socket, buffer, len);
        }
        else if (len == 0)
        {
            if (s_connectStateCallback != NULL)
                s_connectStateCallback(false);

            std::cerr << "Client disconnected (socket: " << client_socket << ").\n";
            client_active = false;
            break;
        }
        else
        {
            if (errno == EAGAIN || errno == EWOULDBLOCK)
            {
                // 超时检查心跳
                if (++missed_heartbeats >= MAX_MISSED_HEARTBEATS)
                {
                    std::cerr << "No heartbeat received from client (socket: "
                              << client_socket << ") for " << MAX_MISSED_HEARTBEATS * 5
                              << " seconds. Disconnecting...\n";
                    client_active = false;
                }
                continue;
            }
            std::cerr << "Receive error! (socket: " << client_socket << ")\n";
            client_active = false;
            break;
        }
    }

    // 客户端断开连接
    close(client_socket);
    current_client_socket = -1;

    // 重启广播线程
    {
        std::lock_guard<std::mutex> lock(broadcast_mutex);
        broadcasting = true; // 启用广播
    }
    broadcast_cv.notify_one(); // 通知广播线程重新开始广播

    return nullptr;
}

void *ServerSocket::sendHeartbeat(void *arg)
{
    int client_socket = *(int *)arg;
    bool client_active = true;

    while (client_active)
    {
        time_t current_time = time(nullptr);
        time_t last_active = last_data_time.load();

        // 如果超过5秒没有数据交互，发送心跳
        if (current_time - last_active >= 5)
        {

            // 发送心跳消息
            int result = send(client_socket, HEARTBEAT_MSG.data(), HEARTBEAT_MSG.size(), 0);

            // 如果发送失败（可能客户端已断开），退出心跳线程
            if (result <= 0)
            {
                std::cerr << "Failed to send heartbeat to client (socket: " << client_socket << "). Stopping heartbeat thread." << std::endl;
                break;
            }

            printf("Heartbeat sent to client (socket: %d) after 5 seconds of inactivity\n", client_socket);

            // 更新最后一次活动时间，避免连续发送心跳
            last_data_time = current_time;
        }

        // 每秒检查一次
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }

    return nullptr;
}

void ServerSocket::stop()
{
    if (!is_running)
        return;
    is_running = false;

    // 关闭当前客户端连接
    if (current_client_socket != -1)
    {
        close(current_client_socket);
        pthread_join(client_thread, nullptr);
        // pthread_join(heartbert_thread, nullptr);
        current_client_socket = -1;
    }

    // 关闭服务端套接字
    if (server_fd >= 0)
    {
        close(server_fd);
        server_fd = -1;
    }

    printf("Server stopped.\n");
}

void ServerSocket::processReceivedData(const unsigned char *buffer, size_t received_len, int client_socket)
{
    // 将新接收到的数据与剩余数据合并
    size_t total_len = remainingData.size() + received_len;
    std::vector<unsigned char> completeData(total_len);

    // 拷贝剩余数据
    std::copy(remainingData.begin(), remainingData.end(), completeData.begin());
    // 拷贝新接收到的数据
    std::copy(buffer, buffer + received_len, completeData.begin() + remainingData.size());

    size_t index = 0; // 当前解析位置

    while (index < total_len)
    {
        // 确保有足够的字节数读取头部
        if (index + sizeof(MessageHeader) > total_len)
        {
            // 如果不够，保存剩余数据
            remainingData = std::vector<unsigned char>(completeData.begin() + index, completeData.end());
            std::cerr << "This is not a complete frame of data, waiting for the next reception!" << std::endl;
            return; // 数据不完整，等待下次接收
        }

        // 读取消息头
        MessageHeader *header = reinterpret_cast<MessageHeader *>(&completeData[index]);
        size_t msg_length = header->msgLength; // 获取消息长度

        // 确保整个消息可用
        if (index + sizeof(MessageHeader) + msg_length > total_len)
        {
            // 如果不够，保存剩余数据
            remainingData = std::vector<unsigned char>(completeData.begin() + index, completeData.end());
            std::cerr << "This is not a complete frame of data, waiting for the next reception!" << std::endl;
            return; // 数据不完整，等待下次接收
        }

        // 处理具体消息
        // if(isHeartbeat(&completeData[index + sizeof(MessageHeader)], msg_length)){
        if (isHeartbeat(&completeData[index], msg_length))
        {
            // 处理心跳
            missed_heartbeats.store(0); // 收到心跳，重置计数器
            printf("Received heartbeat from client (socket: %d)\n", client_socket);
        }
        else if (isSetDataTypeCommand(&completeData[index], msg_length))
        {
            // 处理数据类型设置命令
            printf("Client (socket: %d) sent setting dataType command\n", client_socket);
            send(client_socket, CORRECT_SOCKET_MSG.data(), CORRECT_SOCKET_MSG.size(), 0);
            last_data_time = time(nullptr);
            // 获取匹配的枚举值
            RequestType requestType = getRequestType(combineBytes(completeData[index + sizeof(MessageHeader) + 0],
                                                                  completeData[index + sizeof(MessageHeader) + 1]));
            RequestTag requsetTag = getRequestTag(combineBytes(completeData[index + sizeof(MessageHeader) + 2],
                                                               completeData[index + sizeof(MessageHeader) + 3]));

            Request req(requestType, requsetTag, 0, 0);
            if (s_msgCallback != NULL)
                s_msgCallback(MSG_SET_DATA_TYPE, req);
            else
                std::cerr << "Error: on callback set!" << std::endl;
        }
        else if (isSetModelCommand(&completeData[index], msg_length))
        {
            // 处理模型设置命令
            printf("Client (socket: %d) sent setting model command\n", client_socket);
            send(client_socket, CORRECT_SOCKET_MSG.data(), CORRECT_SOCKET_MSG.size(), 0);
            last_data_time = time(nullptr);
            // 获取匹配的枚举值
            RequestType requestType = getRequestType(combineBytes(completeData[index + sizeof(MessageHeader) + 0],
                                                                  completeData[index + sizeof(MessageHeader) + 1]));
            RequestTag requsetTag = getRequestTag(combineBytes(completeData[index + sizeof(MessageHeader) + 2],
                                                               completeData[index + sizeof(MessageHeader) + 3]));
            int modelVersion = combineBytes(completeData[index + sizeof(MessageHeader) + 4],
                                            completeData[index + sizeof(MessageHeader) + 5]);
            Request req(requestType, requsetTag, 0, modelVersion);
            if (s_msgCallback != NULL)
                s_msgCallback(MSG_SET_MODEL, req);
            else
                std::cerr << "Error: on callback set!" << std::endl;
        }
        else if (isSetDataLenCommand(&completeData[index], msg_length))
        {
            // 处理数据长度设置命令
            printf("Client (socket: %d) sent setting dataLen command\n", client_socket);
            send(client_socket, CORRECT_SOCKET_MSG.data(), CORRECT_SOCKET_MSG.size(), 0);
            last_data_time = time(nullptr);
            uint32_t dataLen = combineTo32Bit(completeData[index + sizeof(MessageHeader) + 0],
                                              completeData[index + sizeof(MessageHeader) + 1],
                                              completeData[index + sizeof(MessageHeader) + 2],
                                              completeData[index + sizeof(MessageHeader) + 3]);
            Request req(RequestType::NONE, RequestTag::NONE, dataLen, 0);
            if (s_msgCallback != NULL)
                s_msgCallback(MSG_SET_DATA_MS, req);
            else
                std::cerr << "Error: on callback set!" << std::endl;
        }
        else if (isSetPixelsCommand(&completeData[index], msg_length))
        {
            // 处理分辨率设置命令
            printf("Client (socket: %d) sent request pixels command\n", client_socket);
            send(client_socket, CORRECT_SOCKET_MSG.data(), CORRECT_SOCKET_MSG.size(), 0);
            last_data_time = time(nullptr);
            uint32_t pixelsW = combineBytes(completeData[index + sizeof(MessageHeader) + 0],
                                            completeData[index + sizeof(MessageHeader) + 1]);
            uint32_t pixelsH = combineBytes(completeData[index + sizeof(MessageHeader) + 2],
                                            completeData[index + sizeof(MessageHeader) + 3]);
            Request req(RequestType::NONE, RequestTag::NONE, 0, 0, pixelsW, pixelsH);
            if (s_msgCallback != NULL)
                s_msgCallback(MSG_SET_PIXESL_WH, req);
            else
                std::cerr << "Error: on callback set!" << std::endl;
        }
        else if (isPcRequestCommand(&completeData[index], msg_length))
        {
            // 处理请求命令
            printf("Client (socket: %d) sent request data command\n", client_socket);
            send(client_socket, CORRECT_SOCKET_MSG.data(), CORRECT_SOCKET_MSG.size(), 0);
            last_data_time = time(nullptr);
            Request req;
            if (s_msgCallback != NULL)
                s_msgCallback(MSG_REQUEST, req);
            else
                std::cerr << "Error: on callback set!" << std::endl;
        }
        else if (isPcRequestBatteryCommand(&completeData[index], msg_length))
        {
            // 处理电池请求命令
            printf("Client (socket: %d) sent request battery command\n", client_socket);
            send(client_socket, CORRECT_SOCKET_MSG.data(), CORRECT_SOCKET_MSG.size(), 0);
            last_data_time = time(nullptr);
            Request req;
            if (s_msgCallback != NULL)
                s_msgCallback(MSG_REQUEST_BATTERY, req);
            else
                std::cerr << "Error: on callback set!" << std::endl;
        }

        // 处理完当前消息后，移动到下一个消息的开始位置
        index += sizeof(MessageHeader) + msg_length;
    }

    // 清空 remainingData, 因为所有数据都已解析
    remainingData.clear();
}

// 新增心跳检测方法
bool ServerSocket::isHeartbeat(const unsigned char *data, size_t len)
{
    // 如果长度不是 0，直接返回 false
    if (len != 0)
    {
        return false;
    }

    // 使用 memcmp 比较 data 和 HEARTBEAT_MSG，判断是否相等
    return memcmp(data, HEARTBEAT_MSG.data(), HEARTBEAT_MSG.size()) == 0;
}
// 检查是否为断开指令
bool ServerSocket::isCloseCommand(const unsigned char *data, size_t len)
{
    if (len != 8)
    {
        return false;
    }
    return memcmp(data, CLOSE_SOCKET_MSG.data(), CLOSE_SOCKET_MSG.size()) == 0;
}
// 检查是否为设置类：数据类型指令
bool ServerSocket::isSetDataTypeCommand(const unsigned char *data, size_t len)
{
    // 定义消息格式，假设消息长度为6
    // 第0字节：消息类型
    // 第1字节：后续字节的数量（可以放置长度, 比如为0x04）
    // 第2字节及以后的字节用于其他特定的数据，比如数据类型标识符

    return ((len == 4) && data[0] == MSG_SET_DATA_TYPE);
}
bool ServerSocket::isSetModelCommand(const unsigned char *data, size_t len)
{
    return ((len == 6) && data[0] == MSG_SET_MODEL);
}
bool ServerSocket::isSetDataLenCommand(const unsigned char *data, size_t len)
{
    return ((len == 4) && data[0] == MSG_SET_DATA_MS);
}
bool ServerSocket::isSetPixelsCommand(const unsigned char *data, size_t len)
{
    return ((len == 4) && data[0] == MSG_SET_PIXESL_WH);
}
bool ServerSocket::isPcRequestCommand(const unsigned char *data, size_t len)
{
    return (len == 0 && data[0] == MSG_REQUEST);
}
bool ServerSocket::isPcRequestBatteryCommand(const unsigned char *data, size_t len)
{
    return ((len == 2 && data[0] == MSG_REQUEST_BATTERY));
}